package com.example.server.exception;

import com.example.server.bean.Admin;
import com.example.server.bean.Menu;
import com.example.server.util.RespBean;
import com.example.server.dao.MenuDao;
import io.netty.channel.ConnectTimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.ConnectException;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * ProjectName: yeb
 * Author: 别怿言
 * Date: 2023-02-06 21:26
 * Description：全局异常处理
 */
@RestControllerAdvice
public class GlobalException {

    @Autowired
    private MenuDao menuDao;

    @ExceptionHandler(SQLException.class)
    public RespBean mysqlException(SQLException e){
        if(e instanceof SQLIntegrityConstraintViolationException){
            return RespBean.error("该数据有关联数据，删除失败！");
        }
        e.printStackTrace();
        return RespBean.error("数据库异常，删除失败！");
    }

    @ExceptionHandler(ConnectException.class)
    public RespBean mysqlException(ConnectException e){
        if(e instanceof ConnectTimeoutException){
            Integer adminid = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
            List<Menu> menus = menuDao.getMenusByAdminId(adminid);
            return RespBean.error("Redis服务器连接异常，该数据由数据库直接获取！",menus);
        }
        e.printStackTrace();
        return RespBean.error("连接异常，请检查服务器是否在线或者网络异常！");
    }

}
